// 异步加载js文件
const loadJS = (url, target) => {
  return new Promise((resolve, reject) => {
    const scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.async = true;
    scriptTag.src = url;
    scriptTag.onload = scriptTag.onreadystatechange = function () {
      if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        resolve()
      } else {
        reject({
          message: 'javascript 文件加载失败'
        })
      }
    }
    scriptTag.onerror = function () {
      reject({
        message: 'javascript 文件加载失败'
      })
    }
    if (target) {
      document.querySelector(target).appendChild(scriptTag);
    } else {
      document.body.appendChild(scriptTag);
    }
  })
}
// 异步加载css文件
const loadCSS = (url) => {
  return new Promise((resolve, reject) => {
    const linkTag = document.createElement('link');
    linkTag.type = 'text/css';
    linkTag.rel = 'stylesheet';
    linkTag.async = true;
    linkTag.href = url;
    linkTag.onload = linkTag.onreadystatechange = function () {
      if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
        resolve()
      } else {
        reject({
          message: 'css 文件加载失败'
        })
      }
    }
    linkTag.onerror = function () {
      reject({
        message: 'css 文件加载失败'
      })
    }
    document.body.appendChild(linkTag);
  })
}

export {
  loadJS,
  loadCSS
}
